/*
 纯定位功能
 * */
define([], function() {
	function Location(){
		this.props={
			point: {
				x: 0,
				y: 0
			},
			pointLoop:[]
		}
		var that=this;
		this.map=null;
		this.geolocation=null;
		this.geolocationLoop=null;
		this.initAMap=function(){
			if(AMap.Map===undefined){
				this.initAMap();
				return false;
			}
			try {
				this.map = new AMap.Map('', {
					resizeEnable: true
				});
			} catch(e) {
				alert(e.message);
				//TODO handle the exception
			}
			this.map.plugin('AMap.Geolocation', this.initGeolocation);
			return this;
		}
		
		this.initGeolocation=function(){
			var map = that.map;
			//普通定位初始化
			var geolocation = new AMap.Geolocation({
				enableHighAccuracy: true, //是否使用高精度定位，默认:true
				timeout: 10000, //超过10秒后停止定位，默认：无穷大
				zoomToAccuracy: false, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				buttonPosition: 'RB'
			});
			that.geolocation = geolocation;
			map.addControl(geolocation);
			AMap.event.addListener(geolocation, 'complete', that.onComplete); //返回定位信息
			AMap.event.addListener(geolocation, 'error', that.onError); //返回定位出错信息
			//循环定位对象初始化
			that.geolocationLoop=new AMap.Geolocation({
				enableHighAccuracy: true, //是否使用高精度定位，默认:true
				timeout: 10000, //超过10秒后停止定位，默认：无穷大
				zoomToAccuracy: false, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				buttonPosition: 'RB'
			});
			map.addControl(that.geolocationLoop);
			AMap.event.addListener(that.geolocationLoop, 'complete', that.onCompleteLoop); //返回定位信息
			AMap.event.addListener(that.geolocationLoop, 'error', that.onError); //返回定位出错信息	
		}
		
		this.getlocation=function(callback){
			try {
				that.pointcallback = callback;
				if(!that.geolocation){
					var st=setTimeout(function(){
						if(that.geolocation){
							that.geolocation.getCurrentPosition();
							clearInterval(st)
						}
					},500)
				}
				else{
					that.geolocation.getCurrentPosition();
				}
				
			} catch(e) {
				alert(2 + e.message);
			}
		}
		//获取当前位置的定位数据。
		this.pointcallback=function(data){
			console.log('data');
		}
		
		/*
		*开启循环定位
		*timeout:每次定位的时间间隔（单位：s）
		*/
		this.openLoopLocation=function(timeout){
			var sec;
			that.props.pointLoop=[];
			console.log(that.loopFun);
			if(typeof(timeout)==='number'){
				sec=timeout*1000;
			}
			else{
				sec=parseFloat(timeout)*1000;
			}
			that.loopFun=setInterval(function(){
				that.geolocationLoop.getCurrentPosition();
			},sec);			
		}
		
		//关闭循环定位
		this.closeLoopLocation=function(){
			clearInterval(this.loopFun);
			//alert(Location.props.pointLoop);
			return that.props.pointLoop;
		}
		
		//解析循环定位结果
		this.onCompleteLoop= function(data) {
			that.props.pointLoop.push([data.position.lng, data.position.lat])
		}
		//解析定位结果
		this.onComplete= function(data) {
			that.pointcallback(JSON.stringify(data));	
		}
		//解析定位错误信息
		this.onError= function(data) {
			alert('定位失败')
			that.pointcallback(JSON.stringify(data));
		}
		
		return this.initAMap();
	}
	return new Location();
})